#include "StorageManager.h"
#include <EEPROM.h>

void StorageManager::begin() {
  EEPROM.get(Storage::ADDR_BASE, _data);
  if (_data.magic != Storage::MAGIC) {
    _data.magic = Storage::MAGIC;
    _data.lifetimeSeedCount = 0;
    _data.lifetimeRuntimeSeconds = 0;
    _data.soilDryRaw = 900; 
    _data.soilWetRaw = 300;  
    _dirty = true;
    flushNow();
  }
}

void StorageManager::addSeeds(uint32_t n) {
  if (n == 0) return;
  _data.lifetimeSeedCount += n;
  _dirty = true;
}

void StorageManager::tickRuntime(unsigned long nowMs) {
  if (_lastRuntimeTickMs == 0) { _lastRuntimeTickMs = nowMs; return; }
  unsigned long elapsed = nowMs - _lastRuntimeTickMs;
  if (elapsed >= 1000) {
    _data.lifetimeRuntimeSeconds += elapsed / 1000;
    _lastRuntimeTickMs = nowMs - (elapsed % 1000);
    _dirty = true;
  }
}

void StorageManager::setSoilCalibration(int16_t dryRaw, int16_t wetRaw) {
  _data.soilDryRaw = dryRaw;
  _data.soilWetRaw = wetRaw;
  _dirty = true;
  flushNow(); 
}

void StorageManager::resetLifetimeStats() {
  _data.lifetimeSeedCount = 0;
  _data.lifetimeRuntimeSeconds = 0;
  _dirty = true;
  flushNow();
}

void StorageManager::flushIfDue(unsigned long nowMs) {
  if (_dirty && (nowMs - _lastFlushMs >= SAVE_INTERVAL_MS)) {
    flushNow();
  }
}

void StorageManager::flushNow() {
  EEPROM.put(Storage::ADDR_BASE, _data);
  _dirty = false;
  _lastFlushMs = millis();
}
